package com.oocl.o2o.admin.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.oocl.o2o.admin.dao.ComplaintInfoDao;
import com.oocl.o2o.admin.dao.MerchantDao;
import com.oocl.o2o.admin.entity.ComplaintInfo;
import com.oocl.o2o.admin.entity.Merchant;
import com.oocl.o2o.admin.service.ComplaintInfoService;
import com.oocl.o2o.admin.vo.ComplainVO;
import com.oocl.o2o.admin.vo.ComplaintsVo;
import com.oocl.o2o.connectutil.dto.ComplaintDTO;

@Service(value="complaintInfoServiceImpl")
public class ComplaintInfoServiceImpl implements ComplaintInfoService{

	@Resource(name="complaintInfoDaoImpl")
	private ComplaintInfoDao complaintInfoDao;
	
	@Resource(name="merchantDaoImpl")
	private MerchantDao merchantDao;
	
	@Override
	public ComplaintInfo findById(String id) {
		// TODO Auto-generated method stub
		return complaintInfoDao.findById(id);
	}

	@Override
	public List<ComplaintInfo> findAll() {
		// TODO Auto-generated method stub
		return complaintInfoDao.findAll();
	}


	@Override
	@Transactional
	public List<ComplaintsVo> findByMerchantId(String merchantId) {
		// TODO Auto-generated method stub
		List<ComplaintInfo> complaintInfos = complaintInfoDao.findByMerchantId(merchantId);
		List<ComplaintsVo> list = new ArrayList<ComplaintsVo>();
		for (ComplaintInfo complaintInfo : complaintInfos) {
			ComplaintsVo complaintsVo = new ComplaintsVo(complaintInfo.getId(), complaintInfo.getMerchant().getUname(), complaintInfo.getMerchant().getStatus(), complaintInfo.getContent(), complaintInfo.getSendDate());
			list.add(complaintsVo);
		}
		return list;
	}
	
	@Override
	@Transactional
	public ComplaintInfo saveComplaintInfo(ComplaintDTO complaintDTO) {
		// TODO Auto-generated method stub

		ComplaintInfo complaintInfo = new ComplaintInfo();	
		Merchant merchant = merchantDao.findByName(complaintDTO.getMerchantName());
		
		if(merchant!=null){
			complaintInfo.setMerchant(merchant);
			complaintInfo.setContent(complaintDTO.getReason());	
			complaintInfoDao.add(complaintInfo);
			return complaintInfo;
		}else{
			System.out.println("投诉商家不存在！");
			return null;
		}
	}


	@Override
	@Transactional
	public List<ComplainVO> findAllComplaintByMerchant() {
		List<ComplainVO> list = new ArrayList<ComplainVO>();
		List<Merchant> merchants = complaintInfoDao.findAllByMerchant();
		if(merchants == null){
			return null;
		}else{
			for(Merchant m : merchants){
				if(m.getComplaintInfoSet().size()>0){
					ComplainVO complainVO = new ComplainVO(m.getId(), m.getUname(), m.getStatus(), m.getComplaintInfoSet().size());
					list.add(complainVO);
				}
			}
			//排序
			Collections.sort(list);
		}
		return list;
	}




}
